/*
	Copyright (c) 2011 Canadensys
*/
package net.canadensys.dataportal.vascan.config;

import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;

import net.canadensys.dataportal.vascan.config.impl.InstallationConfigValidator;

/**
 * Abstract class to allow different type of Configuration Validator.
 * Generic validation functions are kept here.
 */
public abstract class AbstractConfigValidator {

	public abstract boolean validateConfiguration(InstallationConfigIF targetedConfiguration);
	
	/**
	 * This function checks if a mandatory configuration value can be found.
	 * @param key
	 * @return
	 */
	protected boolean testMandatoryConfiguration(InstallationConfigIF targetedConfiguration, String key){
		if(targetedConfiguration.get(key) == null){
			Logger.getLogger(InstallationConfigValidator.class.getName()).log(Level.SEVERE, targetedConfiguration.toString() + ":The property " + key + " is mandatory.");
			return false;
		}
		return true;
	}
	
	/**
	 * This function checks if the folder represented by the key exists and if it has the proper permissions.
	 * If the folder doesn't exists, the function will try to create it.
	 * @param key
	 * @return true if the folder exists with the proper permissions or if the folder was successfully created. Otherwise, false.
	 */
	protected boolean testAndSetWorkFolder(InstallationConfigIF targetedConfiguration, String key){
		String folderPath = targetedConfiguration.get(key);
		File folderToTest = new File(folderPath);
		if(folderToTest.exists()){
			if(!(folderToTest.canRead() && folderToTest.canWrite())){
				Logger.getLogger(InstallationConfigValidator.class.getName()).log(Level.SEVERE, targetedConfiguration.toString() + " needs read and write access to folder " + folderPath + " defined by configuration key " + key);
				return false;
			}
		}
		else{ //try to create the directory structure
			if(!folderToTest.mkdirs()){
				Logger.getLogger(InstallationConfigValidator.class.getName()).log(Level.SEVERE, targetedConfiguration.toString() + " could not create the folder " + folderPath + 
						" defined by configuration key " + key);
				return false;
			}
		}
		return true;
	}

}
